﻿using Common.Library.Logs;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Library.Db
{
    public class SqlBulkCopyExt
    {

        #region 批量插入
        /// <summary>  
        /// 批量插入
        /// </summary>  
        /// <param name="conStr">数据库连接串</param>
        /// <param name="strTableName">数据库中对应的表名</param>  
        /// <param name="dtData">数据集</param>  
        public virtual void BulkInsert(string conStr, string strTableName, DataTable dtData)
        {
            try
            {
                //引用SqlBulkCopy  
                using (SqlBulkCopy sqlRevdBulkCopy = new SqlBulkCopy(conStr))
                {
                    sqlRevdBulkCopy.DestinationTableName = strTableName;//数据库中对应的表名  
                    sqlRevdBulkCopy.NotifyAfter = dtData.Rows.Count;//有几行数据  
                    sqlRevdBulkCopy.WriteToServer(dtData);//数据导入数据库  
                    sqlRevdBulkCopy.Close();//关闭连接  
                }
            }
            catch (Exception ex)
            {
                FileLog.WriteLog(System.Reflection.MethodInfo.GetCurrentMethod().Name, "", ex.Message, ErrorType.异常BUG);
            }
        }

        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="conStr"></param>
        /// <param name="strTableName"></param>
        /// <param name="list"></param>
        public virtual void BulkInsert<T>(string conStr, string strTableName, List<T> list)
        {
            DataTable dt = DataTableConvert.ToDataTable(list);
            BulkInsert(conStr, strTableName, dt);
        }
        #endregion

    }
}
